{% extends "stock/template.html" %}
{% load staticfiles %}
{% block title %}Stock View{% endblock %}

{% block content %}

<div class="row cl" style="margin-left: 20px;margin-top: 20px;">
    <!-- 为ECharts准备一个具备大小（宽高）的Dom -->
    <div id="main" style="width: 1000px;height:900px;"></div>
</div>
{% endblock %}

{% block ext-jss %}
<!-- 引入 echarts.js -->
<script src="https://cdn.jsdelivr.net/npm/echarts@4.8.0/dist/echarts.min.js"></script>
{% endblock %}

{% block script %}
<script type="text/javascript">
var upColor = '#ec0000';
var downColor = '#00da3c';
var okColor = '#888888';
var cid01 = '#ffcc00';
var cid02 = '#ff0000';
var cid03 = '#00da3c';
var cid04 = '#6699ff';
var cid05 = '#cc6633';

function splitData(rawData) {
    var categoryData = [];
    var values = [];
    var volumes = [];
    var metaData = {
        code: rawData['data']['code'],
        market: rawData['data']['market'],
        name: rawData['data']['name'],
        dktotal: rawData['data']['dktotal']
    };
    pbcData = rawData['pbc'];
    rawData = rawData['data']['klines'];


    for (var i = 0; i < rawData.length; i++) {
        rawData[i] = rawData[i].split(',');
        rawData[i] = [rawData[i][0], parseFloat(rawData[i][1]), parseFloat(rawData[i][2]), parseFloat(rawData[i][3]), parseFloat(rawData[i][4]), parseFloat(rawData[i][5]), parseFloat(rawData[i][6]), parseFloat(rawData[i][7]), parseFloat(rawData[i][8]), parseFloat(rawData[i][9])];
        categoryData.push(rawData[i].splice(0, 1)[0]);
        values.push(rawData[i]);
        volumes.push([i, rawData[i][4], rawData[i][0] > rawData[i][1] ? -1 : 1]);
    }

    return {
        metaData: metaData,
        categoryData: categoryData,
        values: values,
        volumes: volumes,
        pbcData: pbcData
    };
}

function calculateMA(dayCount, data) {
    var result = [];
    for (var i = 0, len = data.values.length; i < len; i++) {
        if (i < dayCount) {
            result.push('-');
            continue;
        }
        var sum = 0;
        for (var j = 0; j < dayCount; j++) {
            sum += data.values[i - j][1];
        }
        result.push(+(sum / dayCount).toFixed(3));
    }
    return result;
}

function calculateValue(indx, data) {
    var result = [];
    for (var i = 0, len = data.values.length; i < len; i++) {
        result.push(data.values[i][indx]);
    }
    return result;
}

function getData(code, echarts_box_id) {
    // 基于准备好的dom，初始化echarts实例
    var myChart = echarts.init(document.getElementById(echarts_box_id));
    // 显示加载动画
    myChart.showLoading();

    {#var stockCode = "0.000001";#}
    var stockCode = code.trim();
    //console.log("stockCode: " + stockCode);

    //var stockUrl = "http://push2his.eastmoney.com/api/qt/stock/kline/get?fields1=f1,f2,f3,f4,f5,f6,f7,f8,f9,f10,f11,f12,f13&fields2=f51,f52,f53,f54,f55,f56,f57,f58,f59,f61&beg=0&end=20500101&ut=fa5fd1943c7b386f172d6893dbfba10b&rtntype=6&secid=" + stockCode + "&klt=101&fqt=1";
    //console.log("stockUrl: " + stockUrl);
    {#$.get(stockUrl, function (rawData) {#}
    $.get('/stock/get-json-data/' + stockCode).done(function (rawData) {
        var data = splitData(rawData);
        //console.log(data);
        var gp_name = data.metaData['name'];
        var gp_code = data.metaData['market']+'.'+data.metaData['code'];
        $("#gp_code").text(gp_code);
        $("#gp_name").text(gp_name);

        // 隐藏加载动画
        myChart.hideLoading();
        myChart.setOption(option = {
            backgroundColor: '#fff',
            animation: false,
            legend: {
                bottom: 10,
                left: 'center',
                data: ['日线数据', '换手率', 'MA5', 'MA10', 'MA20', 'MA30', 'MLF', 'TMLF', '逆回购']
            },
            title: {
                text: '【'+gp_name+'】'+'日线与央行公开市场业务交易对比图',
                subtext: '数据来自央行官网及东方财富官网',
                left: 'center',
                align: 'right'
            },
            tooltip: {
                trigger: 'axis',
                axisPointer: {
                    type: 'cross'
                },
                backgroundColor: 'rgba(245, 245, 245, 0.8)',
                borderWidth: 1,
                borderColor: '#ccc',
                padding: 10,
                textStyle: {
                    color: '#000'
                },
                position: function (pos, params, el, elRect, size) {
                    var obj = {top: 10};
                    obj[['left', 'right'][+(pos[0] < size.viewSize[0] / 2)]] = 30;
                    return obj;
                },
                formatter: function (param) {
                    var tooltipList = [];
                    var curDate = "";
                    //var seriesIndexList = [6, 7];
                    for (var i=0; i < param.length; i++) {
                        //console.log("ID: ", i, "name: ", param[i].name, "seriesIndex: ", param[i].seriesIndex, "seriesName: ", param[i].seriesName, "data: ", param[i].data);
                        var item = "";
                        if (param[i].seriesIndex === 0) {
                            curDate = '<b>日期: ' + param[i].name + '</b><hr size=1 style="margin: 3px 0">';
                            //console.log("id0_curDate: ", curDate);
                            item = '开盘: <span>' + param[i].data[1] + '</span><br/>'+
                                '收盘: <span style="color: \' + param[i].color + \'">' + param[i].data[2] + '</span><br/>'+
                                '最高: <span>' + param[i].data[3] + '</span><br/>'+
                                '最低: <span>' + param[i].data[4] + '</span><br/>'+
                                '涨跌幅: <span style="color: ' + param[i].color + '">' + param[i].data[8] + '%</span><br/>'
                        } else if (param[i].seriesIndex >= 6) {
                            curDate = '<b>日期: ' + param[i].name + '</b><hr size=1 style="margin: 3px 0">';
                            item = param[i].seriesName + ': <span style="color: ' + param[i].color + '">' + param[i].data[1] + '</span><br/>';
                        } else {
                            item = param[i].seriesName + ': <span style="color: ' + param[i].color + '">' + param[i].data + '</span><br/>';
                        }
                        tooltipList.push(item);
                    }
                    tooltipList.unshift(curDate);
                    return tooltipList.join('');
                }
                // extraCssText: 'width: 170px'
            },
            axisPointer: {
                link: {xAxisIndex: 'all'},
                label: {
                    backgroundColor: '#777'
                }
            },
            toolbox: {
                feature: {
                    dataZoom: {
                        yAxisIndex: false
                    },
                    brush: {
                        type: ['lineX', 'keep', 'clear']
                    }
                }
            },
            brush: {
                xAxisIndex: 'all',
                brushLink: 'all',
                outOfBrush: {
                    colorAlpha: 0.3
                }
            },
            visualMap: [
                {
                    show: false,
                    seriesIndex: 6,
                    dimension: 2,
                    pieces: [{
                        label: '买入',
                        value: 1,
                        color: upColor
                    }, {
                        label: '卖出',
                        value: -1,
                        color: downColor
                    }]
                },
                {
                    show: false,
                    seriesIndex: 9,
                    dimension: 2,
                    pieces: [{
                        label: '合理充裕',
                        value: 1,
                        color: cid01
                    }, {
                        label: '较高水平',
                        value: 2,
                        color: cid02
                    }, {
                        label: '逆回购',
                        value: 3,
                        color: cid03
                    }]
                }
            ],
            grid: [
                {
                    left: '10%',
                    right: '8%',
                    height: '24%'
                },
                {
                    left: '10%',
                    right: '8%',
                    top: '31%',
                    height: '16%'
                },
                {
                    left: '10%',
                    right: '8%',
                    top: '52%',
                    height: '35%'
                }
            ],
            xAxis: [
                {
                    type: 'category',
                    data: data.categoryData,
                    scale: true,
                    boundaryGap: false,
                    axisLine: {onZero: false},
                    splitLine: {show: false},
                    splitNumber: 20,
                    min: 'dataMin',
                    max: 'dataMax',
                    axisPointer: {
                        z: 100
                    }
                },
                {
                    type: 'category',
                    gridIndex: 1,
                    data: data.categoryData,
                    scale: true,
                    boundaryGap: false,
                    axisLine: {onZero: false},
                    axisTick: {show: false},
                    splitLine: {show: false},
                    axisLabel: {show: false},
                    splitNumber: 20,
                    min: 'dataMin',
                    max: 'dataMax'
                },
                {
                    type: 'category',
                    gridIndex: 2,
                    data: data.categoryData,
                    scale: true,
                    boundaryGap: false,
                    axisLine: {onZero: false},
                    {#axisTick: {show: false},#}
                    splitLine: {show: false},
                    {#axisLabel: {show: false},#}
                    splitNumber: 20,
                    min: 'dataMin',
                    max: 'dataMax'
                }
            ],
            yAxis: [
                {
                    scale: true,
                    splitArea: {
                        show: true
                    }
                },
                {
                    name: '（%）',
                    type: 'value',
                    scale: true,
                    position: 'right',
                    splitNumber: 5,
                    axisLabel: {
                        formatter: '{value}%'
                    },
                    axisLine: {show: true},
                    axisTick: {show: true},
                    splitLine: {show: false}
                },
                {
                    scale: true,
                    gridIndex: 1,
                    splitNumber: 2,
                    axisLabel: {show: false},
                    axisLine: {show: false},
                    axisTick: {show: false},
                    splitLine: {show: false}
                },
                {
                    name: '交易金额（亿元）',
                    scale: true,
                    show: true,
                    gridIndex: 2,
                    splitNumber: 2,
                    {#axisLabel: {show: false},#}
                    {#axisLine: {show: false},#}
                    {#axisTick: {show: false},#}
                    {#splitLine: {show: false}#}
                }
            ],
            dataZoom: [
                {
                    type: 'inside',
                    xAxisIndex: [0, 1, 2],
                    start: 95,
                    end: 100
                },
                {
                    show: true,
                    xAxisIndex: [0, 1, 2],
                    type: 'slider',
                    top: '90%',
                    start: 93,
                    end: 100,
                }
            ],
            series: [
                {
                    name: '日线数据',
                    type: 'candlestick',
                    data: data.values,
                    itemStyle: {
                        color: upColor,
                        color0: downColor,
                        borderColor: null,
                        borderColor0: null
                    },
                    tooltip: {
                        formatter: function (param) {
                            param = param[0];
                            return [
                                'Date: ' + param.name + '<hr size=1 style="margin: 3px 0">',
                                'Open: ' + param.data[0] + '<br/>',
                                'Close: ' + param.data[1] + '<br/>',
                                'Highest: ' + param.data[2] + '<br/>',
                                'Lowest: ' + param.data[3] + '<br/>'
                            ].join('');
                        }
                    }
                },
                {
                    name: '换手率',
                    type: 'line',
                    yAxisIndex: 1,
                    color: '#9999CC',
                    data: calculateValue(8, data),
                    smooth: true,
                    lineStyle: {
                        opacity: 0.5
                    }
                },
                {
                    name: 'MA5',
                    type: 'line',
                    data: calculateMA(5, data),
                    smooth: true,
                    lineStyle: {
                        opacity: 0.5
                    }
                },
                {
                    name: 'MA10',
                    type: 'line',
                    data: calculateMA(10, data),
                    smooth: true,
                    lineStyle: {
                        opacity: 0.5
                    }
                },
                {
                    name: 'MA20',
                    type: 'line',
                    data: calculateMA(20, data),
                    smooth: true,
                    lineStyle: {
                        opacity: 0.5
                    }
                },
                {
                    name: 'MA30',
                    type: 'line',
                    data: calculateMA(30, data),
                    smooth: true,
                    lineStyle: {
                        opacity: 0.5
                    }
                },
                {
                    name: '成交数',
                    type: 'bar',
                    xAxisIndex: 1,
                    yAxisIndex: 2,
                    data: data.volumes
                },
                {
                    name: 'TMLF',
                    type: 'bar',
                    stack: '总量',
                    color: cid05,
                    areaStyle: {},
                    xAxisIndex: 2,
                    yAxisIndex: 3,
                    data: pbcData.tmlf.amount_cid
                },
                {
                    name: 'MLF',
                    type: 'bar',
                    stack: '总量',
                    color: cid04,
                    areaStyle: {},
                    xAxisIndex: 2,
                    yAxisIndex: 3,
                    data: pbcData.mlf.amount_cid
                },
                {
                    name: '逆回购',
                    type: 'bar',
                    stack: '总量',
                    {#color: cid03,#}
                    areaStyle: {},
                    xAxisIndex: 2,
                    yAxisIndex: 3,
                    /*label: {
                        normal: {
                            show: true,
                            position: 'top'
                        }
                    },*/
                    data: pbcData.reverse_repo.amount_cid
                }
            ]
        }, true);

        myChart.dispatchAction({
            type: 'brush',
            areas: [
                {#{#}
                {#    brushType: 'lineX',#}
                {#    coordRange: ['2020-03-01', '2020-05-01'],#}
                {#    xAxisIndex: 0#}
                {#}#}
            ]
        });
    });
}


$(function () {
    getData("{{ stock_code }}", 'main');
});
</script>
{% endblock %}
